﻿using XiangziProjectTemplete.Core.Api.Common;
using XiangziProjectTemplete.Core.Common.Helper;
using XiangziProjectTemplete.Core.Common.HttpContextUser;
using XiangziProjectTemplete.Core.Extensions.Others;
using XiangziProjectTemplete.Core.IServices;
using XiangziProjectTemplete.Core.Model;
using XiangziProjectTemplete.Core.Model.CommonModel;
using XiangziProjectTemplete.Core.Model.Enums.XiangziProjectTemplete.LESPublicCommon;
using XiangziProjectTemplete.Core.Model.Models;
using XiangziProjectTemplete.Core.Model.ParamModels;
using XiangziProjectTemplete.Core.Model.ViewModels.XiangziProjectTemplete;
using XiangziProjectTemplete.Core.Utility;
using LesCCService;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace XiangziProjectTemplete.Core.Api.Controllers
{
    /// <summary> 
    /// 叫料工单 
    /// </summary> 
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize(Permissions.Name)]
    public class Les_CallOrderController : ControllerBase
    {
        private readonly ILes_CallOrderServices _Les_CallOrderServices;
        private readonly IUser _user;
        private readonly IBase_CodeItemsServices _base_CodeItemsServices;
        private readonly IV_CallOrderServices _v_CallOrderServices;
        private readonly ILogger<Les_StockInfoController> _logger;
        private readonly IBase_StationServices _base_StationServices;
        private readonly ILes_ProcedureRoleServices _les_ProcedureRoleServices;
        private readonly IBase_UserStationServices _base_UserStationServices;

        public Les_CallOrderController(
            IBase_UserStationServices base_UserStationServices,
            ILes_ProcedureRoleServices les_ProcedureRoleServices,
            IBase_StationServices base_StationServices,
            ILogger<Les_StockInfoController> logger,
            IV_CallOrderServices v_CallOrderServices,
            ILes_CallOrderServices Les_CallOrderServices, IBase_CodeItemsServices base_CodeItemsServices, IUser user)
        {
            this._base_UserStationServices = base_UserStationServices;
            this._les_ProcedureRoleServices = les_ProcedureRoleServices;
            this._base_StationServices = base_StationServices;
            this._logger = logger;
            _Les_CallOrderServices = Les_CallOrderServices;
            _user = user;
            _base_CodeItemsServices = base_CodeItemsServices;
            this._v_CallOrderServices = v_CallOrderServices;
        }

        /// <summary> 
        /// 分页获取叫料工单列表 
        /// </summary> 
        /// <param name="param">筛选条件</param> 
        /// <returns>获取结果</returns> 
        [HttpPost]
        public async Task<MessageModel<PageModel<V_CallOrder>>> Get([FromBody] V_CallOrderParam param)
        {
            if (string.IsNullOrEmpty(param.searchVal) || string.IsNullOrWhiteSpace(param.searchVal))
            {
                param.searchVal = string.Empty;
            }

            var whereConditions = WhereConditionsExtensions.GetWhereConditions<V_CallOrder, V_CallOrderParam>(param);
            if (!whereConditions.IsSuccess)
            {
                return new MessageModel<PageModel<V_CallOrder>>()
                {
                    msg = whereConditions.ErrMsg,
                    success = false,
                    response = null
                };
            }

            #region 根据工序权限进行过滤
            SeeProcedureRoleViewModel seeProcedureRoleViewModel = await _les_ProcedureRoleServices.GetProcedureListByUser(_user);
            List<int> proList = new List<int>();
            if (seeProcedureRoleViewModel.IsHasAllProcedure)
            {//全部权限

            }
            else
            {
                proList = seeProcedureRoleViewModel.ProcedureList;
                Expression<Func<V_CallOrder, bool>> whereExpression2 = a => a.AllowProcedure != null && proList.Contains(Convert.ToInt32(a.AllowProcedure));
                whereConditions.data = whereConditions.data.And(whereExpression2);
            }

            #endregion

            #region 根据用户进行过滤所能看到的站点权限
            SeeUserStationViewModel seeStationView = await _base_UserStationServices.GetSeeStationListByUser(_user);
            List<int> seeStationList = new List<int>();
            if (seeStationView != null && seeStationView.StationIdList.Count > 0)
            {
                seeStationList = seeStationView.StationIdList;
                Expression<Func<V_CallOrder, bool>> whereExpression2 = a => seeStationList.Contains(Convert.ToInt32(a.StationId));
                whereConditions.data = whereConditions.data.And(whereExpression2);
            }
            #endregion

            var newQueryData = await _v_CallOrderServices.QueryPage(whereConditions.data, param.page, param.pageSize, " CreateTime desc ");

            return new MessageModel<PageModel<V_CallOrder>>()
            {
                msg = "获取成功",
                success = true,
                response = newQueryData
            };

        }

        /// <summary> 
        /// 获取单个叫料工单 
        /// </summary> 
        /// <param name="id">主键</param> 
        /// <returns>获取结果</returns> 
        [HttpGet]
        public async Task<MessageModel<Les_CallOrder>> Get(int id = 0)
        {
            return new MessageModel<Les_CallOrder>()
            {
                msg = "获取成功",
                success = true,
                response = await _Les_CallOrderServices.QueryById(id)
            };
        }


        /// <summary>
        /// 根据 配料工作号 查找 已经分拣完成的，并且指定物料的库存信息,用户界面提示
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<MessageModel<string>> GetBufferStockListByWorkNoForAlert([FromBody] Les_CallOrder request)
        {
            var data = new MessageModel<string>();

            try
            {
                #region 验证
                MessageModel<string> retBody = null;
                retBody = ValidateDataHelper.CommonValidateIsNULL<Les_CallOrder, string>(request);
                if (retBody != null)
                {
                    return retBody;
                }

                List<ValidateModel> columnsList = null;
                columnsList = new List<ValidateModel>() {
                   new ValidateModel(){ ChinaName="配料任务号", DataType=typeof(string), DataValue=request.BurdenWorkNo },
                   new ValidateModel(){ ChinaName="物料", DataType=typeof(string), DataValue=request.MaterialCodeItemId },
                };
                retBody = ValidateDataHelper.CommonValidate<Les_CallOrder, string>(request, columnsList);
                if (retBody != null)
                {
                    return retBody;
                }
                //*/

                #endregion
                GetBufferStockListByWorkNoParam param = new GetBufferStockListByWorkNoParam()
                {
                    BurdenWorkNo = request.BurdenWorkNo,
                    MaterialCodeItemId = request.MaterialCodeItemId,
                    StoreArea = Model.Enums.XiangziProjectTemplete.StoreAreaEnum.StoreBuffer

                };
                string requestStr = JsonConvert.SerializeObject(param);
                using (LesCCService.LesCCServiceClient client = new LesCCService.LesCCServiceClient())
                {
                    SdaResEntity sdaRes = await client.GetBufferStockListByWorkNoForAlertAsync(requestStr);
                    if (sdaRes.resultk__BackingField)
                    {
                        return MessageModel<string>.Success(sdaRes.resMsgk__BackingField);
                    }
                    else
                    {
                        return MessageModel<string>.Fail(sdaRes.resMsgk__BackingField);
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "根据 配料工作号 查找 已经分拣完成的，并且指定物料的库存信息,用户界面提示出现异常:" + ex.Message);
                return MessageModel<string>.Fail("根据 配料工作号 查找 已经分拣完成的，并且指定物料的库存信息,用户界面提示出现异常:" + ex.Message);
            }
        }

        /// <summary> 
        /// 验证叫料工单 
        /// </summary> 
        /// <param name="request">要新增的叫料工单对象</param> 
        /// <returns></returns> 
        [HttpPost]
        [AllowAnonymous]
        public async Task<MessageModel<string>> ValidateCreateCallOrder([FromBody] Les_CallOrder request)
        {
            var data = new MessageModel<string>();

            try
            {
                #region 验证
                MessageModel<string> retBody = null;
                retBody = ValidateDataHelper.CommonValidateIsNULL<Les_CallOrder, string>(request);
                if (retBody != null)
                {
                    return retBody;
                }

                #endregion

                string requestStr = JsonConvert.SerializeObject(request);
                return await WcfService.ValidateCreateCallOrder(requestStr);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "校验叫料工单出现异常:" + ex.Message);
                return MessageModel<string>.Fail("校验叫料工单出现异常:" + ex.Message);
            }
        }

        /// <summary> 
        /// 新增叫料工单 
        /// </summary> 
        /// <param name="request">要新增的叫料工单对象</param> 
        /// <returns></returns> 
        [HttpPost]
        public async Task<MessageModel<bool>> Post([FromBody] Les_CallOrder request)
        {
            var data = new MessageModel<bool>();

            try
            {
                #region 验证
                MessageModel<bool> retBody = null;
                retBody = ValidateDataHelper.CommonValidateIsNULL<Les_CallOrder, bool>(request);
                if (retBody != null)
                {
                    return retBody;
                }

                List<ValidateModel> columnsList = null;
                columnsList = new List<ValidateModel>() {
                   new ValidateModel(){ ChinaName="呼叫模式", DataType=typeof(int), DataValue=request.LesTaskMode },
                   new ValidateModel(){ ChinaName="所属工序", DataType=typeof(string), DataValue=request.AllowProcedure },
                   new ValidateModel(){ ChinaName="站点", DataType=typeof(int), DataValue=request.StationId },
                };
                retBody = ValidateDataHelper.CommonValidate<Les_CallOrder, bool>(request, columnsList);
                if (retBody != null)
                {
                    return retBody;
                }


                #region 验证用户是否登出

                var isUserLogout = LesApiCommon.IsUserLogout<bool>(_user);
                if (isUserLogout != null) return isUserLogout;

                #endregion


                //*/
                LesTaskModeEnum lesTaskModeEnum = (LesTaskModeEnum)Enum.Parse(typeof(LesTaskModeEnum), request.LesTaskMode.ToString());

                switch (lesTaskModeEnum)
                {
                    case LesTaskModeEnum.呼叫物料:
                    case LesTaskModeEnum.余料或空托盘回库并呼叫物料:
                        if (string.IsNullOrEmpty(request.BurdenWorkNo))
                        {
                            return MessageModel<bool>.Fail("配料任务号不能为空");
                        }
                        if (string.IsNullOrEmpty(request.MaterialCodeItemId))
                        {
                            return MessageModel<bool>.Fail("物料不能为空");
                        }
                        break;
                }

                #endregion

                var result = await WcfService.CreateCallOrder(request, null, _user.Name, _user.ID);
                if (result.success)
                {
                    return MessageModel<bool>.Success("成功");
                }
                else
                {
                    return MessageModel<bool>.Fail(result.msg);
                }

            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "新增叫料工单出现异常:" + ex.Message);
                return MessageModel<bool>.Fail("新增叫料工单出现异常:" + ex.Message);
            }
        }

        /// <summary> 
        /// 更新叫料工单 
        /// </summary> 
        /// <param name="request">要更新的叫料工单对象</param> 
        /// <returns>更新结果</returns> 
        [HttpPut]
        public async Task<MessageModel<string>> Put([FromBody] Les_CallOrder request)
        {
            var data = new MessageModel<string>();
            if (request.Id != string.Empty)
            {
                request.ModifyTime = DateTime.Now;
                request.ModifyBy = _user.Name;
                request.ModifyId = _user.ID;
                request.OperationRemark = "更新";
                data.success = await _Les_CallOrderServices.Update(request);
                if (data.success)
                {
                    data.msg = "更新成功";
                    data.response = request?.Id.ObjToString();
                }
            }

            return data;
        }

        /// <summary> 
        /// 删除叫料工单 
        /// </summary> 
        /// <param name="id">主键</param> 
        /// <returns>删除结果</returns> 
        [HttpDelete]
        public async Task<MessageModel<string>> Delete(int id = 0)
        {
            var data = new MessageModel<string>();
            if (id > 0)
            {
                var detail = await _Les_CallOrderServices.QueryById(id);
                if (detail != null)
                {
                    data.success = await _Les_CallOrderServices.DeleteById(detail.Id);
                    if (data.success)
                    {
                        data.msg = "删除成功";
                        data.response = detail?.Id.ObjToString();
                    }
                }
            }

            return data;
        }

        /// <summary> 
        /// 逻辑删除叫料工单 
        /// </summary> 
        /// <param name="id">主键</param> 
        /// <returns>删除结果</returns> 
        [HttpDelete]
        public async Task<MessageModel<string>> LogicDelete(int id = 0)
        {
            var data = new MessageModel<string>();
            if (id > 0)
            {
                var detail = await _Les_CallOrderServices.QueryById(id);
                detail.ModifyTime = DateTime.Now;
                detail.ModifyBy = _user.Name;
                detail.ModifyId = _user.ID;
                detail.IsDeleted = true;
                detail.OperationRemark = "删除";

                if (detail != null)
                {
                    data.success = await _Les_CallOrderServices.Update(detail);
                    if (data.success)
                    {
                        data.msg = "删除成功";
                        data.response = detail?.Id.ObjToString();
                    }
                }
            }

            return data;
        }
    }
}
